package cn.dglydrpy.fundmanagement.service.impl;

import cn.dglydrpy.fundmanagement.service.ITushareService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.HashMap;

@Service
public class TushareService implements ITushareService {

    @Value("${tushare.token}")
    private String token;
    
    @Override
    public void getAllStockInfo() throws IOException {
        // 空实现，保持接口兼容性
    }
    
    /**
     * 获取股票某时段的历史净值
     *
     * @param tsCode    股票代码，例如：000001.SH
     * @param sdate
     * @param edate
     * @param apiName
     * @return Map，键为日期，值为收盘价
     */
    public Map<String, BigDecimal> getStockHistoryData(String tsCode, String sdate, String edate, String apiName) {

        LocalDate endDate = LocalDate.parse(edate);
        LocalDate startDate = LocalDate.parse(sdate);
        
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String startDateStr = startDate.format(formatter);
        String endDateStr = endDate.format(formatter);
        
        System.out.println("查询参数: ts_code=" + tsCode + ", start_date=" + startDateStr + ", end_date=" + endDateStr);
        
        Map<String, BigDecimal> historyData = new HashMap<>();
        
        try {
            String response = sendTushareRequest(tsCode, startDateStr, endDateStr,apiName);
            parseTushareResponse(response, historyData);
            System.out.println("成功获取到" + historyData.size() + "条数据");
        } catch (Exception e) {
            System.err.println("获取股票历史数据时发生错误: " + tsCode);
            System.err.println("错误信息: " + e.getMessage());
            e.printStackTrace();
        }
        
        return historyData;
    }
    
    /**
     * 发送请求到Tushare API
     * @param tsCode 股票代码/指数代码
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @param apiName api名
     * @return API响应字符串
     * @throws IOException
     */
    private String sendTushareRequest(String tsCode, String startDate, String endDate,String apiName) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost("http://api.tushare.pro");
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            
            // 构造请求参数
            JSONObject params = new JSONObject();
            params.put("ts_code", tsCode);
            params.put("start_date", startDate);
            params.put("end_date", endDate);
            
            // 构造请求体
            JSONObject requestBody = new JSONObject();
            requestBody.put("api_name", apiName);
            requestBody.put("token", token);
            requestBody.put("params", params);
            requestBody.put("fields", "trade_date,close");
            
            StringEntity entity = new StringEntity(requestBody.toJSONString(), "UTF-8");
            httpPost.setEntity(entity);
            
            CloseableHttpResponse response = httpClient.execute(httpPost);
            try {
                return EntityUtils.toString(response.getEntity(), "UTF-8");
            } finally {
                response.close();
            }
        } finally {
            httpClient.close();
        }
    }
    
    /**
     * 解析Tushare API响应
     * @param response API响应字符串
     * @param historyData 存储解析结果的Map
     */
    private void parseTushareResponse(String response, Map<String, BigDecimal> historyData) {
        JSONObject jsonResponse = JSON.parseObject(response);
        if (jsonResponse.getInteger("code") != 0) {
            System.err.println("Tushare API返回错误: " + jsonResponse.getString("msg"));
            return;
        }
        
        JSONObject data = jsonResponse.getJSONObject("data");
        if (data == null) {
            System.err.println("Tushare API返回数据为空");
            return;
        }
        
        JSONArray fields = data.getJSONArray("fields");
        JSONArray items = data.getJSONArray("items");
        
        if (fields == null || items == null) {
            System.err.println("Tushare API返回数据格式不正确");
            return;
        }
        
        // 查找trade_date和close字段的索引
        int dateIndex = -1;
        int closeIndex = -1;
        for (int i = 0; i < fields.size(); i++) {
            String field = fields.getString(i);
            if ("trade_date".equals(field)) {
                dateIndex = i;
            } else if ("close".equals(field)) {
                closeIndex = i;
            }
        }
        
        if (dateIndex == -1 || closeIndex == -1) {
            System.err.println("Tushare API返回数据缺少必要字段");
            return;
        }
        
        // 解析数据
        for (int i = 0; i < items.size(); i++) {
            JSONArray item = items.getJSONArray(i);
            String tradeDate = item.getString(dateIndex);
            BigDecimal close = item.getBigDecimal(closeIndex);
            historyData.put(tradeDate.substring(0,4)+"-"+tradeDate.substring(4,6)+"-"+tradeDate.substring(6), close);
        }
    }
}